package App.OO.service;

import App.Model.Interface.MessageType;
import App.Model.message.Message;
import App.OO.service.thread.CtoSThread;
import App.OO.service.thread.Manage.ManageCtoSThread;

import javax.imageio.stream.FileImageInputStream;
import java.io.*;
import java.util.Date;

//传输文件
public class OOFileCService {

    public void sendFileToOne(String src, String fileName, String senderId, String getterId,int mode,String fileLengthStr) {
        //mode:1 服务器暂存,2 大文件在线传输
        //获取src文件 -> FileMessage
        Message message = new Message();
        message.setContent("向你发送了一个文件 " + fileName + "  " + fileLengthStr);
        message.setMesType(MessageType.MESSAGE_FILE_MSG);
        message.setFileuniquenum(System.currentTimeMillis());//文档的唯一标识时间
        message.setSender(senderId);
        message.setGetter(getterId);
        message.setSendTime(new Date());
        message.setSrc(src);
        message.setDest("src\\main\\resources\\recourse\\download\\" + fileName);
        //获取本机文件
        FileInputStream fileInputStream = null;
        byte[] fileBytes = new byte[(int) new File(src).length()];

        try {
            fileInputStream = new FileInputStream(src);
            fileInputStream.read(fileBytes);//将文件读取到fileBytes上去
            //包装完成message
            message.setFileBytes(fileBytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null)
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        try {
            CtoSThread ctoSThread = ManageCtoSThread.getCtoSThread(senderId);
            ObjectOutputStream oos = new ObjectOutputStream(ctoSThread.getSocket().getOutputStream());
            oos.writeObject(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void getSourceAtServiceFile(String userId,String sender,long uniqueNum,String dest,boolean isGet){
        //请求获取文件
        Message message = new Message();
        message.setSender(userId);
        message.setDest(dest);
        message.setGetter(sender);
        message.setFileuniquenum(uniqueNum);
        message.setSendTime(new Date());
        if(isGet){
            message.setMesType(MessageType.MESSAGE_FILE_MSG_GET);
        }else {
            message.setMesType(MessageType.MESSAGE_FILE_MSG_NOTGET);
        }

        //发送向服务器
        try {
            ObjectOutputStream oos =
                    new ObjectOutputStream((ManageCtoSThread.getCtoSThread(userId)).getSocket().getOutputStream());
            oos.writeObject(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
